package com.electromagnetic.industry.software.manage.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.electromagnetic.industry.software.common.enums.EffectFlagEnum;
import com.electromagnetic.industry.software.common.pojo.UserLoginInfo;
import com.electromagnetic.industry.software.common.util.UserThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

@Component
public class EdMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createdTime")) {
            this.setFieldValByName("createdTime", new Date(), metaObject);
        }
        if (metaObject.hasGetter("createdBy")) {
            this.setFieldValByName("createdBy", Optional.ofNullable(UserThreadLocal.getUser()).map(UserLoginInfo::getUserId).orElse(""), metaObject);
        }
        if (metaObject.hasGetter("updatedTime")) {
            this.setFieldValByName("updatedTime", new Date(), metaObject);
        }
        if (metaObject.hasGetter("updatedBy")) {
            this.setFieldValByName("updatedBy", Optional.ofNullable(UserThreadLocal.getUser()).map(UserLoginInfo::getUserId).orElse(""), metaObject);
        }
        if (metaObject.hasGetter("effectFlag")) {
            this.setFieldValByName("effectFlag", EffectFlagEnum.EFFECT.code, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updatedTime")) {
            this.setFieldValByName("updatedTime", new Date(), metaObject);
        }
        if (metaObject.hasGetter("updatedBy")) {
            this.setFieldValByName("updatedBy", Optional.ofNullable(UserThreadLocal.getUser()).map(UserLoginInfo::getUserId).orElse(""), metaObject);
        }
    }
}

